// // permission.js 是控制页面登录权限的文件，
// // 主要使用 beforeEach 路由前置守卫 根据 Token 存在与否，控制页面间的跳转
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import router, { asyncRoutes } from './router'// 引入静态路由
const writeList = ['/login', '/404']
import getPageTitle from '@/utils/get-page-title'
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token

  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      router.myrouter = to.fullPath

      //
      if (!store.getters.userId) {
        const menus = await store.dispatch('user/getUserInfo')

        const filterRoutes = asyncRoutes.filter(route => {
          const routeName = route.children[0].name
          return menus.includes(routeName)
        })
        // 用来作为路由跳转的目标信息
        router.addRoutes(filterRoutes)

        filterRoutes.push(
          { path: '*', redirect: '/404', hidden: true }
        )

        // 存到vuex里面用作渲染左边栏
        store.commit('permission/setRoutes', filterRoutes)
        next({
          path: to.fullPath, // 保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else { // 如果有userid
        // 所有的静态路由和动态路由
        let allPath = store.state.permission.routes.map(item => item.path)
        // 所有的路由里面没有首页和员工详情
        const otherPath = [
          '/dashboard',
          '/employees/detail'
        ]
        // 全部完整的地址
        allPath = [...allPath, ...otherPath]
        // 检测所有地址里面, 不包含要去的地址
        if (!allPath.includes(to.path)) {
          if (router.myrouter) {
            next('/')
          } else {
            next('/404')
          }
        } else {
          next()
        }
      }
    }
  } else {
    if (writeList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.afterEach((to, from) => {
  // 隐藏进度条
  NProgress.done()
})
